<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="isUpdate ? t('action.edit') : t('action.create')" @ok="handleSubmit" :width="900">
    <BasicForm @register="registerForm" >
      <template #specIdsSlot>
        <JVxeTable
          ref="specsTableRef"
          :columns="specIdsSchema"
          toolbar
          :toolbarConfig="toolbarConfig"
          resizable
          asyncRemove
          rowNumber
          :dataSource="specsDataSource"
        >
          <template #tableAction="props">
            <Popconfirm title="确定删除吗？" @confirm="onDeleteSpecsRow(props)">
              <a>{{ t('action.delete') }}</a>
            </Popconfirm>
          </template>
        </JVxeTable>
      </template>
      <template #action="{ record }">
        <TableAction :actions="itemsRowAction(record)" />
      </template>
    </BasicForm>
    <template #appendFooter>
      <a-button type="primary" @click="saveAndNext">{{ t('action.saveAndNext') }}</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { JVxeTableInstance } from '/@/components/jeecg/JVxeTable/types';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema,specIdsSchema} from './multiSpec.data';
  import { saveOrUpdate, getById } from './multiSpec.api';
  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  const isUpdate = ref(true);
  const toolbarConfig = {
    btn: ['add','remove'],
  };
  const specsTableRef = ref<JVxeTableInstance>();
    const specsDataSource = ref<any[]>([]);
  const { t } = useI18n();
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    //labelWidth: 150,
    // layout: 'inline',
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    specsDataSource.value = [];
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //获取详情
      const result = await getById({ id: data?.record?.id });
      if (result && result.specs) {
        specsDataSource.value = result?.specs || [];
      }
      
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  async function getSpecsData() {
    let specsDataValid = true;
    let specsData: Recordable[] = [];
    if (!specsDataValid) {
      throw { errorFields: [{ name: ['specs'] }] };
    }
    specsData = specsTableRef.value!.getTableData();
    return specsData;
  }

  async function onDeleteSpecsRow({ row }) {
    console.log("row:",row)
    // 调用删除方法
    /* const res = await specsTableRef.value?.removeRows(row);
    if (res && res.rows.length > 0) {
      createMessage.success('删除成功');
    } */
  }

  function itemsRowAction(record) {
    return [
      {
        label: t('action.delete'),
        onClick: handleItemsEdit.bind(null, record),
      },
    ];
  }

  function handleItemsEdit(record) {
    console.log(111111111111111)
    console.log(record);
  }

  /**
   * 保存并继续
   */
  function saveAndNext() {
    handleSubmit(false);
  }

  //表单提交事件
  async function handleSubmit(data) {
    try {
      const values = await validate();
      values.specs = await getSpecsData();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      if (data) {
        closeModal();
      } else {
        resetFields();
      }
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
